package com.zrkj.util;

import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RsaUtils {

    private static final String ALGORITHM = "RSA";
    public static String IOT_TOKEN = "";

    /**
     * 使用公钥加密
     *
     * @param string
     * @return 用户密码+公钥
     */
    public static String encrypt(String string, String pubKey) {
        try {
            byte[] decoded = Base64.getDecoder().decode(pubKey);
            PublicKey publicKey = KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(decoded));
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.getEncoder().encodeToString(cipher.doFinal(string.getBytes()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
//    public static void main(String[] args) {
//        String encrypt = encrypt("123456", "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCm+zugZbtwk0a/mW4mFBbPtxl3LGMkntysTnTbDO8GRL3QDofLIq/vgdu19/TW2qGozte7rKnnkn1sUSvXpXLobXJ663/hqt/7yXzMHy6ts8aiucKhHTqKVawnRbrigL/jYxx1pYqmaQKHEiPkWgsS4aW+fWgzx2o+jD8KIJQjHwIDAQAB");
//        System.out.println(encrypt);
//    }
}
